<?php

namespace App\Console\Commands\Fix;

use App\Console\BaseCommand;
use App\Consts\GlobalConst;
use App\Models\UserCollect;
use App\Models\UserCollectPackage;
use Illuminate\Database\Query\Builder;

/**
 * 收藏状态修复脚本
 * Class CollectFixCommand
 * @package App\Console\Commands\Fix
 */
class CollectFixCommand extends BaseCommand
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:collect {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'fix collect status';

    /**
     * 收藏状态 - 取消收藏
     * @return int
     */
    public function cancel()
    {
        $subMode = $this->_getPackageSubModel();
        $finish = $subMode->count();
        // 每 100 单位合并处理一次
        $subMode->chunkById(100, function ($list) use ($finish) {
            foreach ($list as $item) {
                static $index = 1;
                $id = $item->collect_package_id;
                // 修复收藏状态
                $collect = $this->_getCollectSubModel($id)->get()->toArray();
                if ($collect) {
                    $info = PHP_EOL;
                    foreach ($collect as $value) {
                        $value = collect($value)->toArray();
                        service()->CollectService->cancelCollect($value);
                        $info .= "[$index/$finish] update collect status - " . json_encode($value);
                    }
                } else {
                    $info = "[$index/$finish] check user collect - package id - " . $id;
                }
                // log info
                $this->info($info);
                if ($collect) $this->logger($info, false, 'script');
                $index++;
            }
        }, 'collect_package_id');
        return 1;
    }

    /**
     * get sub model
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|mixed
     */
    private function _getPackageSubModel()
    {
        $subMode = UserCollectPackage::getSubModel(function (Builder $query) {
            $query->where('is_deleted', GlobalConst::IS_DELETED);
        }, ['id', 'collect_package_id']);
        return $subMode;
    }

    /**
     * get sub model
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|mixed
     */
    private function _getCollectSubModel($id)
    {
        $subMode = UserCollect::getSubModel(function (Builder $query) use($id) {
            $query->where('package_id', $id);
            $query->where('is_deleted', GlobalConst::IS_NOT_DELETE);
        }, ['id', 'user_id', 'package_id', 'target_id', 'target_type']);
        return $subMode;
    }

}
